package com.lin.codesandbox.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.lin.codesandbox.codesandbox.model.ExecuteCodeRequest;
import com.lin.codesandbox.codesandbox.model.ExecuteCodeResponse;
import com.lin.codesandbox.codesandbox.model.ExecuteMessage;
import com.lin.codesandbox.codesandbox.model.JudgeInfo;
import com.lin.codesandbox.utils.ProcessUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Component
public class JavaNativeCodeSandbox implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
//    private static final String SECURITY_MANAGER_PATH = "D:\\src\\main\\resources\\security";
//    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";
    public static void main(String[] args) {
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1","3"));
        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java",StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        JavaNativeCodeSandbox codeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        Long startTime = System.currentTimeMillis();
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在，没有则新建
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        Path currentRelativePath = Paths.get("");
        Path absolutePath = currentRelativePath.toAbsolutePath();
        System.out.println(absolutePath);

//        String tempPath = absolutePath.toString() + "\\src\\main\\resources\\testCode\\test\\pom.xml";
        // C:\Mcd\cloud-native\cloud-native-code-sandbox\src\main\resources\cloudnative-test
//        String tempPath = absolutePath.toString() + "/src/main/resources/cloudnative-test/pom.xml";
        String tempPath = absolutePath.toString() + "/src/main/resources/cloudnative-test/pom.xml";
        //编译代码  mvn -f D:\test\pom.xml clean install -Dmaven.test.skip=true
        // cmd /c mvn -f %s install -Dmaven.test.skip=true
        String compileCommand = String.format("cmd /c mvn -f %s install -Dmaven.test.skip=true", tempPath);
        System.out.println(compileCommand);
        StringBuilder finalMessage = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(compileCommand);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "打包");
            if(StringUtils.isNotEmpty(executeMessage.getMessage()))
                finalMessage.append(executeMessage.getMessage());
            if(StringUtils.isNotEmpty(executeMessage.getErrorMessage()))
                finalMessage.append(executeMessage.getErrorMessage());
            System.out.println(executeMessage);//输出每一次的编译结果
        } catch (IOException e) {
            errorResponse(e);
        }
        // testCode\test\target\webui-test-0.0.1-SNAPSHOT.jar
        // /root/lhx/test/pom.xml
        //执行代码，得到输出结果
//        String jarPath = absolutePath.toString() + "\\src\\main\\resources\\testCode\\test\\target\\webui-test-0.0.1-SNAPSHOT.jar";
//        String jarPath = "D:\\test\\target\\webui-test-0.0.1-SNAPSHOT.jar";
        // C:\Mcd\cloud-native\cloud-native-code-sandbox\src\main\resources\cloudnative-test\target\webui-test-0.0.1-SNAPSHOT.jar
        String jarPath = absolutePath.toString() + "/src/main/resources/cloudnative-test/target/webui-test-0.0.1-SNAPSHOT.jar";
        String exeCmd = String.format("java -jar %s",jarPath);
        System.out.println(exeCmd);
        try {
            Process process = Runtime.getRuntime().exec(exeCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "执行");
            if(StringUtils.isNotEmpty(executeMessage.getMessage()))
                finalMessage.append(executeMessage.getMessage());
            if(StringUtils.isNotEmpty(executeMessage.getErrorMessage()))
                finalMessage.append(executeMessage.getErrorMessage());
            System.out.println(executeMessage);//输出每一次的运行结果信息
        } catch (IOException e) {
            errorResponse(e);
        }
//        List<ExecuteMessage> executeMessageList = new ArrayList<>();
//        for(String inputArgs : inputList){
////            String exeCmd = String .format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s",userCodeParentPath,SECURITY_MANAGER_PATH,SECURITY_MANAGER_CLASS_NAME,inputArgs);
//            String exeCmd = String .format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
//            try {
//                Process process = Runtime.getRuntime().exec(exeCmd);
//                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "执行");
//                System.out.println(executeMessage);//输出每一次的运行结果信息
//                executeMessageList.add(executeMessage);
//            } catch (IOException e) {
//                errorResponse(e);
//            }
//        }
        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
//        for(ExecuteMessage executeMessage : executeMessageList){
//            Integer exitValue = executeMessage.getExitValue();
//            String message = executeMessage.getMessage();
//            String errorMessage = executeMessage.getErrorMessage();
//            Long time = executeMessage.getTime();
//            Long memory = executeMessage.getMemory();
//
//            if(StrUtil.isNotBlank(errorMessage)){
//                executeCodeResponse.setMessage(errorMessage);
//                //用户提交的代码无法执行成功
//                executeCodeResponse.setStatus(1);
//                break;
//            }
//            outputList.add(executeMessage.getMessage());
//            if(time!=null){
//                maxTime=Math.max(maxTime,time);
//            }
//        }
//        if(outputList.size() == executeMessageList.size()){
//            //某些用例执行失败
//            executeCodeResponse.setStatus(3);
//        }
        JudgeInfo judgeInfo = new JudgeInfo();
        Long endTime = System.currentTimeMillis();
        judgeInfo.setTime(endTime - startTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setMessage(finalMessage.toString());

        //清理文件，释放空间
        if(userCodeFile.getParentFile() != null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    /**
     * 打印异常信息
     * @param e
     * @return
     */
    private ExecuteCodeResponse errorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;

    }
}
